/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package ibmmodel3;

import java.io.IOException;
import java.util.Iterator;
import java.util.Properties;
import java.util.logging.Level;
import java.util.logging.Logger;
import jdbm.RecordManager;
import jdbm.RecordManagerFactory;
import jdbm.RecordManagerOptions;
import jdbm.htree.HTree;

/**
 *
 * @author mwh
 */
public class VocabularyTableJDBM implements VocabularyTable {

    RecordManager recman;

    HTree vocabulary;


    public VocabularyTableJDBM(VocabularyTableMem vtMem, String dbName) throws IOException {

        Properties props = new Properties();

        props.setProperty(RecordManagerOptions.DISABLE_TRANSACTIONS, "true");

        recman = RecordManagerFactory.createRecordManager("/home/mwh/DGS/databases/" + dbName + ".jdbm", props);

        // Create idToName hash-vocabulary and add TOP as element;
        vocabulary = HTree.createInstance(recman);
        recman.setNamedObject("vocabulary", vocabulary.getRecid());

        for (Iterator<String> keyIt = vtMem.keyIterator(); keyIt.hasNext();) {

            String word = keyIt.next();
            int w = vtMem.get(word);

            vocabulary.put(word, w);
            //  System.err.println(key + "  " + dist);
            recman.commit();

        }

        recman.commit();
    }


    public VocabularyTableJDBM(String dbName) throws IOException {


        Properties props = new Properties();

        props.setProperty(RecordManagerOptions.DISABLE_TRANSACTIONS, "true");

        recman = RecordManagerFactory.createRecordManager("/home/mwh/DGS/databases/" + dbName + ".jdbm", props);
        long recid = recman.getNamedObject("vocabulary");

        vocabulary = HTree.load(recman, recid);
    }


    public int get(String word) {
        try {
            Integer res = (Integer) vocabulary.get(word);
            if (res == null) {
                return 1;
            }
            return res;
        } catch (IOException ex) {
            Logger.getLogger(TranslationTableJDBM.class.getName()).log(Level.SEVERE, null, ex);
        }

        return 1;

    }
}
